//
//  YH_UserInfoViewController.m
//  YinHang
//
//  Created by apple on 14-9-17.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_UserInfoViewController.h"
#import "UserInfoTableViewCell.h"
#import "BasicInfoViewController.h"
#import "YH_ChangePasswordViewController.h"

#import "YH_CardMangerViewController.h"//证件管理
#import "YH_MyAccountViewController.h"


@interface YH_UserInfoViewController ()<ASIHTTPRequestDelegate>{
    UITableView *_tableView;
    
    __weak IBOutlet UIView *tipView;//进入积分管理提示界面
    __weak IBOutlet UIView *btn_back_view;//按钮背景界面
    
    __weak IBOutlet UITextField *passwordText;//密码输入框
    __weak IBOutlet UIButton *commit_btn;//提交
    __weak IBOutlet UIButton *cancel_btn;//取消
    
    ASIFormDataRequest *goToAcountRequest;
    MBProgressHUD *postHud;
    //参数
    NSString *action;
    NSDictionary *paramsDict;
}

@end

@implementation YH_UserInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"用户信息";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }

    
    [self setUI];
    
}
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;


}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUI{
//加载TableView
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x+20, self.view.frame.origin.y+40, self.view.frame.size.width-40, 200)];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    
    _tableView.backgroundColor=[UIColor blackColor];
    _tableView.layer.cornerRadius=5.0;
    _tableView.rowHeight=40;
    _tableView.scrollEnabled=NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_tableView];
    //加载tipview
    tipView.hidden = YES;
    tipView.layer.cornerRadius = 5.0;
    btn_back_view.layer.cornerRadius = 5.0;
    commit_btn.layer.cornerRadius = 5.0;
    cancel_btn.layer.cornerRadius = 5.0;
    [commit_btn addTarget:self action:@selector(goToAccount) forControlEvents:UIControlEventTouchUpInside];
    [cancel_btn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{

    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"UserInfoTableViewCell";

   UserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"UserInfoTableViewCell" owner:nil options:nil][0];
      
    }

     NSUInteger row = [indexPath row];
    
    NSArray *textArray=[[NSArray alloc]initWithObjects:@"基本资料",@"我的账户",@"证件管理",@"密码修改",@"自动采集",nil];
    NSArray *imageArray=[[NSArray alloc]initWithObjects:[UIImage imageNamed:@"item_64"],[UIImage imageNamed:@"item_64"],[UIImage imageNamed:@"item_64"],[UIImage imageNamed:@"item_64"],[UIImage imageNamed:@"item_64"],nil];
    
//    [UIImage imageNamed:@"string"]
    
    UIImageView *imageView1 = (UIImageView *)[cell.contentView viewWithTag:1];
    imageView1.image=imageArray[row];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:2];
    label2.text=textArray[row];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    indexPath = [tableView indexPathForSelectedRow];
   NSInteger row= indexPath.row;
    switch (row) {
        case 0:
        {
            BasicInfoViewController *bi_VC =[[BasicInfoViewController alloc]initWithNibName:@"BasicInfoViewController" bundle:nil];
            
            [self.navigationController pushViewController:bi_VC animated:YES];
            
        }
            break;
        case 1:
        {
            passwordText.text = @"";
            tipView.hidden = NO;
            [self.view bringSubviewToFront:tipView];
            _tableView.userInteractionEnabled = NO;
        }
            break;
        case 2:
        {
            
            YH_CardMangerViewController *CM_VC = [[YH_CardMangerViewController alloc]initWithNibName:@"YH_CardMangerViewController" bundle:nil];
            [self.navigationController pushViewController:CM_VC animated:YES];
        }
            break;
        case 3:
        {
            YH_ChangePasswordViewController *cp_VC=[[YH_ChangePasswordViewController alloc]initWithNibName:@"YH_ChangePasswordViewController" bundle:nil];
            [self.navigationController pushViewController:cp_VC animated:YES];
        }break;
        case 4:
        {
            
        } break;
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}

// 返回
- (void)back {
    [goToAcountRequest cancel];
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  进入我的账户
 */
-(void)goToAccount{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在登录，请稍后...";
        }
        
        goToAcountRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        goToAcountRequest.requestMethod = @"POST";
        // 设置超时时间
        goToAcountRequest.timeOutSeconds = 60;
        goToAcountRequest.delegate = self;
        // 设置参数
        NSString *actionStr = @"jifenmima";
        paramsDict = @{@"uid":UNAME,@"mima":passwordText.text};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        goToAcountRequest.postBody = [paramsData mutableCopy];
        
        [goToAcountRequest startAsynchronous];
    }
}
/**
 *  取消
 */
-(void)cancel{
    tipView.hidden = YES;
    _tableView.userInteractionEnabled = YES;
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            _tableView.userInteractionEnabled = YES;
            tipView.hidden = YES;
            YH_MyAccountViewController *myAccount = [[YH_MyAccountViewController alloc]initWithNibName:@"YH_MyAccountViewController" bundle:nil];
            [self.navigationController pushViewController:myAccount animated:YES];
            
        }else if(errorCode == 1){
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            _tableView.userInteractionEnabled = YES;
            tipView.hidden = YES;
            if ([result[@"errorMsg"] isEqualToString:@"密码错误，请重新输入！"]) {
                return;
            }
            YH_MyAccountViewController *myAccount = [[YH_MyAccountViewController alloc]initWithNibName:@"YH_MyAccountViewController" bundle:nil];
            [self.navigationController pushViewController:myAccount animated:YES];
            
        } else {
            [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


-(void)dealloc{
    postHud = nil;
    tipView = nil;
    goToAcountRequest = nil;
    action = nil;
    paramsDict = nil;
}
@end
